﻿//-----------------------------------------------------------------------
// <copyright file="GuildRepository.cs" company="FastNET Services">
//     Copyright (c) 2008-2009. All Rights Reserved.
// </copyright>
// <license>
//     GPLv2
// </license>
// <warranty>
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
//     BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </warranty>
//-----------------------------------------------------------------------
#region Usings

using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Linq;
using GateShift.Common.Repository;
using GateShift.Common.Repository.Interfaces.DataInterfaces;
using GateShift.Common.Repository.Interfaces.Repositories;
using GateShift.Services.GameData.Entities;

#endregion

namespace GateShift.Services.GameData.Repositories
{
    /// <summary>
    /// General repository for managing Guilds
    /// </summary>
    internal class GuildRepository : IGuildRepository
    {
        #region CTor/DTor

        /// <summary>
        /// Initializes a new instance of the GuildRepository class
        /// </summary>
        /// <param name="connection">Reference to the common EntityConnection for the repository</param>
        internal GuildRepository(EntityConnection connection)
        {
            Connection = connection;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets a reference to the common EntityConnection for the repository
        /// </summary>
        protected EntityConnection Connection { get; private set; }

        #endregion

        #region IRepository<IGuildData> Members

        /// <summary>
        /// Retrieves all instances of IGuildData from the repository
        /// </summary>
        /// <returns>List of the requested IGuildData</returns>
        public IList<IGuildData> Retrieve()
        {
            List<IGuildData> returnValues = new List<IGuildData>();

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                foreach (Guild guild in from item in dataSource.Guilds select item)
                {
                    returnValues.Add(guild);
                    dataSource.Detach(guild);
                }
            }

            return returnValues;
        }

        /// <summary>
        /// Retrieves the requested IGuildData by an Identity
        /// </summary>
        /// <param name="ID">Identity to retrieve the data by</param>
        /// <returns>IGuildData instance or null if one was not found</returns>
        /// <exception cref="InvalidCastException">Thrown if the identity is of the wrong type for this datasource</exception>
        public IGuildData Retrieve(Identity ID)
        {
            if (!ID.CanFitInInt64())
            {
                throw new InvalidCastException(string.Format("Identity for this type of repository requires it to be of Int64/int/Int16 Type. Currently is {0}.", ID.UnderlyingType()));
            }

            // This has to be done here because LINQ does not support the inline case
            long searchID = ID;

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                Guild foundGuild = (from
                                           guild
                                           in
                                        dataSource.Guilds
                                    where
                                        guild.GuildID == searchID
                                    select
                                        guild).FirstOrDefault();

                if (foundGuild != null)
                {
                    dataSource.Detach(foundGuild);
                }

                return foundGuild;
            }
        }

        /// <summary>
        /// Deletes the requested IGuildData
        /// </summary>
        /// <param name="Data">IGuildData to delete from the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        /// <exception cref="InvalidOperationException">Thrown if the IGuildData is new or already deleted</exception>
        public void Delete(IGuildData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is Guild))
            {
                throw new InvalidCastException("Data is not of type Guild. Cannot delete this object through this repository");
            }

            if (Data.IsNew)
            {
                throw new InvalidOperationException("Data cannot be new before deleting. There is nothing to delete.");
            }

            if (Data.IsDeleted)
            {
                throw new InvalidOperationException("Data already deleted.");
            }

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                dataSource.Attach((Guild)Data);
                dataSource.DeleteObject(Data);
                dataSource.SaveChanges();
            }
        }

        /// <summary>
        /// Saves the requested IGuildData
        /// </summary>
        /// <param name="Data">IGuildData to save to the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        public void Save(IGuildData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is Guild))
            {
                throw new InvalidCastException("Data is not of type Guild. Cannot save this object through this repository");
            }

            if (!Data.IsDirty)
            {
                return;
            }

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                if (Data.IsNew)
                {
                    dataSource.AddToGuilds((Guild)Data);
                    dataSource.SaveChanges();
                    dataSource.Detach(Data);
                }
                else
                {
                    dataSource.ApplyPropertyChanges("Guilds", Data);
                    dataSource.SaveChanges();
                }
            }
        }

        /// <summary>
        /// Creates a new instance of IGuildData
        /// </summary>
        /// <returns>New Instance of IGuildData</returns>
        public IGuildData Create()
        {
            return new Guild();
        }

        #endregion

        #region IGuildRepository Members

        /// <summary>
        /// Retrieves a single IGuildData by looking at the GuildName
        /// </summary>
        /// <param name="GuildName">Guild name to search by</param>
        /// <returns>IGuildData found or null if no account was found</returns>
        /// <exception cref="ArgumentNullException">Thrown if the search value is null or empty</exception>
        public IGuildData RetrieveByGuildName(string GuildName)
        {
            if (string.IsNullOrEmpty(GuildName))
            {
                throw new ArgumentNullException("GuildName", "A guild name must be provided and cannot be empty");
            }

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                Guild foundGuild = (from
                                           guild
                                           in
                                        dataSource.Guilds
                                    where
                                        guild.Name == GuildName
                                    select
                                        guild).FirstOrDefault();

                if (foundGuild != null)
                {
                    dataSource.Detach(foundGuild);
                }

                return foundGuild;
            }
        }

        /// <summary>
        /// Checks to see if an IGuildData exists by the AccountName
        /// </summary>
        /// <param name="GuildName">Guild name to search by</param>
        /// <param name="IgnoreID">ID of a guild to ignore during check</param>
        /// <returns>Boolean whether or not a guild exists in the system</returns>
        /// <exception cref="ArgumentNullException">Thrown if GuildName is null or empty</exception>
        /// <exception cref="InvalidCastException">Thrown if IgnoreID is of the wrong type for this repository</exception>
        public bool GuildNameExists(string GuildName, Identity? IgnoreID)
        {
            if (string.IsNullOrEmpty(GuildName))
            {
                throw new ArgumentNullException("GuildName", "Must have a guild name to search by");
            }

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                if (IgnoreID.HasValue)
                {
                    if (!IgnoreID.Value.CanFitInInt64())
                    {
                        throw new InvalidCastException("IgnoreID must be of type Int64/int/Int16 for this repository");
                    }

                    long searchID = IgnoreID.Value;
                    return (from
                                    guild
                                    in
                                dataSource.Guilds
                            where
                                guild.Name == GuildName &&
                                guild.GuildID != searchID
                            select
                                guild).Count() > 0;
                }

                return (from
                                guild
                                in
                            dataSource.Guilds
                        where
                            guild.Name == GuildName
                        select
                            guild).Count() > 0;
            }
        }

        #endregion
    }
}